package com.shuogesha.config;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.Retryer;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;

/**
 * Feign请求拦截器（设置请求头，传递请求参数）
 * 
 * @author zhaohaiyuan
 *
 */
@Configuration
public class FeignConfiguration {
	private final Logger logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Bean
	public Retryer feignRetryer() {
		Retryer retryer = new Retryer.Default(100, 1000, 4);
		return retryer;
	}

	@Bean
	public RequestInterceptor requestInterceptor() {
		return requestTemplate -> {
			ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			if (attrs != null) {
				HttpServletRequest request = attrs.getRequest();
				// 如果在Cookie内通过如下方式取
				Cookie[] cookies = request.getCookies();
				if (cookies != null && cookies.length > 0) {
					for (Cookie cookie : cookies) {
						requestTemplate.header(cookie.getName(), cookie.getValue());
					}
				} else {
					logger.warn("FeignHeadConfiguration", "获取Cookie失败！");
				}
				// 如果放在header内通过如下方式取
				Enumeration<String> headerNames = request.getHeaderNames();
				try {
					if (headerNames != null) {
						while (headerNames.hasMoreElements()) {
							String name = headerNames.nextElement();
							String values = request.getHeader(name);
							requestTemplate.header(name, values);
						}
					}
					logger.info("接口路径：" + request.getRequestURL().toString());
					StringBuffer body = new StringBuffer();
					Enumeration<String> bodyNames = request.getParameterNames();
					if (bodyNames != null) {
						Map map = new HashMap();
						while (bodyNames.hasMoreElements()) {
							String name = bodyNames.nextElement();
							String values = request.getParameter(name);
							requestTemplate.query(name, values);
							map.put(name, values);
						}
						logger.info("传入参数：" + map);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	}
}
